package com.funtonow.jqdk.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.adapter.VipAdapter;
import com.funtonow.jqdk.base.BaseFragment;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.UrlUtils;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.bean.VipBean;
import com.funtonow.jqdk.bean.WxPayInfoBean;
import com.funtonow.jqdk.event.PayResultEvent;
import com.funtonow.jqdk.event.UserInfoEvent;
import com.funtonow.jqdk.fkcs.ui.CardActivity;
import com.funtonow.jqdk.ui.LoginActivity;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.TimeUtils;
import com.funtonow.jqdk.utils.ToastUtils;
import com.funtonow.jqdk.widget.ProgressDialogUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.funtonow.jqdk.base.Constants.APP_ID;
import static com.funtonow.jqdk.base.Constants.OWN_APP_ID;
import static com.funtonow.jqdk.base.UrlUtils.BUY_VIP;
import static com.funtonow.jqdk.base.UrlUtils.QUERY_ORDER;
import static com.funtonow.jqdk.base.UrlUtils.VIP_LIST;

/**
 * @author Jiajien
 * @date 2019/6/22
 */
public class VipFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.rlv_vip)
    RecyclerView rlvVip;
    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.tv_user_vip)
    TextView tvUserVip;
    @BindView(R.id.vip_head)
    LinearLayout vipHead;
    @BindView(R.id.tv_vip_agreement)
    TextView tvVipAgreement;

    private VipAdapter vipAdapter;
    private UserInfoBean userInfoBean;
    private VipBean vipBean;
    private IWXAPI api;
    private WxPayInfoBean wxPayInfoBean;
    private Intent intent;


    public static VipFragment newInstance() {
        Bundle args = new Bundle();
        VipFragment fragment = new VipFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View getLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_vip, null);
    }

    @Override
    public void onCreateFragment(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        setAgreement();
        vipHead.setVisibility(View.GONE);
        userInfoBean = SPUtil.getUserInfo();
        initRecyclerView(rlvVip);
        vipAdapter = new VipAdapter();
        rlvVip.setAdapter(vipAdapter);
        getVipList();
        if (userInfoBean != null) {
            tvUserPhone.setText(userInfoBean.getOpenid());
            if (userInfoBean.getVip() != null && userInfoBean.getVip().getDay() > 0 && userInfoBean.getVip().getDay() > System.currentTimeMillis()) {
                tvUserVip.setText(String.format("会员有效期：至%s到期", TimeUtils.dateToString(userInfoBean.getVip().getDay())));
            } else {
                tvUserVip.setText("会员有效期：未开通");
            }
        } else {
            tvUserPhone.setText("未登录");
            tvUserVip.setText("会员有效期：未开通");
        }
        vipAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (SPUtil.getUserInfo() == null) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    appBuyVip(vipAdapter.getItem(position).getProductId());
                }
            }
        });
    }


    private void initRecyclerView(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    private void getVipList() {
        Map<String, String> param = new HashMap<>();
        param.put("appid", OWN_APP_ID);
        HttpUtil.getInstance().postDataAsynToNet(VIP_LIST, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                LogUtil.i(jsonString + " ****************  ");
                vipBean = JSON.parseObject(jsonString, VipBean.class);
                if (vipBean.getErrnum() == 0) {
                    vipAdapter.setNewData(vipBean.getData());
                }

            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    private void appBuyVip(String pid) {
        Map<String, String> param = new HashMap<>();
        param.put("appid", OWN_APP_ID);
        param.put("openid", userInfoBean.getOpenid());
        param.put("pid", pid);
        param.put("wxappid", Constants.APP_ID);
        HttpUtil.getInstance().postDataAsynToNet(BUY_VIP, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                wxPayInfoBean = JSON.parseObject(jsonString, WxPayInfoBean.class);
                if (wxPayInfoBean.getErrnum() == 0) {
                    api = WXAPIFactory.createWXAPI(getActivity(), Constants.APP_ID);
                    api.registerApp(Constants.APP_ID);
                    if (api.isWXAppInstalled()) {
                        PayReq request = new PayReq();
                        request.appId = wxPayInfoBean.getData().getAppid();
                        request.partnerId = wxPayInfoBean.getData().getPartnerid();
                        request.prepayId = wxPayInfoBean.getData().getPrepayid();
                        request.packageValue = wxPayInfoBean.getData().getPaypackage();
                        request.nonceStr = wxPayInfoBean.getData().getNoncestr();
                        request.timeStamp = wxPayInfoBean.getData().getTimestamp();
                        request.sign = wxPayInfoBean.getData().getSign();
                        api.sendReq(request);
                    } else {
                        ToastUtils.show("请安装微信");
                    }
                }
            }

            @Override
            public void failed(Call call, IOException e) {
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void payInfo(PayResultEvent payResultEvent) {
        if (payResultEvent.getType() != 1) {
            queryOrder();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userInfo(UserInfoEvent userInfoEvent) {
        userInfoBean = SPUtil.getUserInfo();
        assert userInfoBean != null;
        tvUserPhone.setText(userInfoBean.getOpenid());
        if (userInfoBean.getVip() != null && userInfoBean.getVip().getDay() > 0 && userInfoBean.getVip().getDay() > System.currentTimeMillis()) {
            tvUserVip.setText(String.format("会员有效期：至%s到期", TimeUtils.dateToString(userInfoBean.getVip().getDay())));
        } else {
            tvUserVip.setText("会员有效期：未开通");
        }
    }

    /**
     * 查询订单状态
     */
    private void queryOrder() {
        Map<String, String> param = new HashMap<>();
        param.put("appid", OWN_APP_ID);
        param.put("wxappid", APP_ID);
        param.put("orderid", wxPayInfoBean.getData().getOrderid());
        HttpUtil.getInstance().postDataAsynToNet(QUERY_ORDER, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                JSONObject jsonObject = JSON.parseObject(jsonString);
                if (jsonObject.getInteger("errnum") == 0) {
                    if (jsonObject.getJSONObject("data").getString("status").equals("SUCCESS")) {
                        if (userInfoBean.getVip() == null) {
                            UserInfoBean.VipBean vipBean = new UserInfoBean.VipBean();
                            vipBean.setDay(jsonObject.getJSONObject("data").getLong("day"));
                            userInfoBean.setVip(vipBean);
                        } else {
                            userInfoBean.getVip().setDay(jsonObject.getJSONObject("data").getLong("day"));
                        }
                        SPUtil.put("userInfo", JSON.toJSONString(userInfoBean));
                        EventBus.getDefault().post(new UserInfoEvent());
                        ToastUtils.show("充值成功");
                        tvUserVip.setText(String.format("会员有效期：至%s到期", TimeUtils.dateToString(jsonObject.getJSONObject("data").getLong("day"))));
                    }
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ProgressDialogUtil.stopProgressDialog();
    }


    @OnClick({R.id.iv_black})
    @Override
    public void onClick(View v) {
        if (SPUtil.getUserInfo() == null) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        } else if (userInfoBean.getVip() != null && userInfoBean.getVip().getDay() > 0
                && userInfoBean.getVip().getDay() > System.currentTimeMillis()) {
            checkOcr();
        } else {
            ToastUtils.show("该服务仅对会员开放");
        }
    }

    private void checkOcr() {
        ProgressDialogUtil.startProgressDialog(getActivity());
        Map<String, String> param = new HashMap<>();
        param.put("appid", OWN_APP_ID);
        param.put("openid", userInfoBean.getOpenid());
        param.put("token", userInfoBean.getToken());
        HttpUtil.getInstance().postDataAsynToNet(UrlUtils.OCR, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                ProgressDialogUtil.stopProgressDialog();
                JSONObject jsonObject = JSON.parseObject(jsonString);
                switch (jsonObject.getInteger("errnum")) {
                    case 0:
                        StatisticsUtils.intentWebView(getActivity(),
                                jsonObject.getString("data"),"黑名单检测","");
                        break;
                    case -2:
                        intent = new Intent(getActivity(), CardActivity.class);
                        intent.putExtra("isBlack", true);
                        startActivity(intent);
                        break;
                    default:
                        ToastUtils.show(jsonObject.getString("data"));
                        break;
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }


    public void setAgreement() {
        String content = "开通即为同意《VIP会员服务协议》";
        SpannableStringBuilder spannable = new SpannableStringBuilder(content);
        spannable.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                StatisticsUtils.intentWebView(getActivity(),
                        Constants.VIP_HTML,getResources().getString(R.string.vip_xy),"");
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }

        }, 6, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan span = new ForegroundColorSpan(getResources().getColor(R.color.color_4E77FF));
        spannable.setSpan(span, 6, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvVipAgreement.setHighlightColor(Color.TRANSPARENT);//去掉点击后的背景颜色为透明
        tvVipAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        tvVipAgreement.setText(spannable);
    }


}
